package com.gzx.spring.apis.tests.xiaoniu;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.DigestUtils;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

//212----R201
public class Demo2 {

	static String secret = "9755d6bdd7226210206b02fa9a733a23513601cf";
	static String appId = "d84d771cc5904979b4666acc824a36a6";
	static String url = "https://api.xndatas.com/gateway/product/query?key=riskScore6";

	public static void main(String[] args) throws Exception {
		String result = "";

		Map<String, String> reqMap = new HashMap<String, String>();
		reqMap.put("mobile", "13488774341");
		reqMap.put("idCard", "210727197902096937");
		reqMap.put("name", "吴岩");

		String sign = sign(reqMap, secret);
		JSONObject bodyParams = new JSONObject();
		bodyParams.put("mobile", reqMap.get("mobile"));
		bodyParams.put("name", reqMap.get("name"));
		bodyParams.put("idCard", reqMap.get("idCard"));
		JSONObject params = new JSONObject();
		params.put("appId", appId);
		params.put("encType ", 1);
		params.put("sign", sign);
		params.put("body", bodyParams.toJSONString());

		result = postHtml(url, params.toJSONString());
		System.out.print(result);
		JSONObject resJson = JSONObject.parseObject(result);
	}

	public static String sign(Map<String, String> paramValues, String secret) {
		try {
			StringBuilder sb = new StringBuilder();
			List<String> paramNames = new ArrayList<>(paramValues.size());
			paramNames.addAll(paramValues.keySet());
			Collections.sort(paramNames);
			for (String paramName : paramNames) {
				sb.append(paramName).append(paramValues.get(paramName));
			}
			sb.append(secret);
			System.out.println(sb.toString());
			return genMd5(sb.toString());
		} catch (Exception e) {
		}
		return null;
	}

	public static String genMd5(String data) {
		return DigestUtils.md5DigestAsHex(data.getBytes(StandardCharsets.UTF_8));
	}

	private static String postHtml(String url, String postData) {
		try {
			URL obj = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			PrintWriter out = new PrintWriter(conn.getOutputStream());
			out.print(postData);
			out.flush();
			BufferedReader br = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
			StringBuffer response = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			br.close();
			return response.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
}
